package com.cloud.calendar.web;

import java.util.List;

import com.cloud.calendar.model.CalendarEvent;
import com.cloud.calendar.service.CalendarService;
import com.cloud.platform.BaseHandler;
import com.cloud.platform.json.JSONArray;
import com.cloud.platform.json.JSONObject;

public class CalendarBean extends BaseHandler {

	private CalendarService calendarService;
	
	private String events;
	
	/**
	 * get calendar events
	 * 
	 * @return
	 */
	public String getEvents() {
		if(events == null) {
			try{
				// search events
				List<CalendarEvent> list = calendarService.searchEvents(getLoginUserId());
				
				// conbine events as json format
				JSONArray eventsArr = new JSONArray();
				JSONObject event = null;
				
				for(CalendarEvent ce : list) {
					event = new JSONObject();
					
					event.put("id", ce.getId());
					event.put("title", ce.getTaskName());
					event.put("start", ce.getStartDate());
					event.put("end", ce.getEndDate());
					event.put("allDay", false);
					
					eventsArr.put(event);
				}
				
				events = eventsArr.toString();
				
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		return events;
	}
	
	/**
	 * update calendar event for dwr
	 * 
	 * @param eventId
	 * @param startDate
	 * @param endDate
	 */
	public void dynUpdateEvent(String eventId, String startDate, String endDate) {
		try{
			calendarService.updateEvent(eventId, startDate, endDate);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * save calendar event for dwr
	 * 
	 * @param startDate
	 * @param taskId
	 * @return
	 */
	public String dynSaveEvent(String startDate, String taskId) {
		String newId = "";
		
		try {
			newId = calendarService.saveEvent(getLoginUserId(), startDate, taskId);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return newId;
	}

	public CalendarService getCalendarService() {
		return calendarService;
	}

	public void setCalendarService(CalendarService calendarService) {
		this.calendarService = calendarService;
	}
	
	public void setEvents(String events) {
		this.events = events;
	}
}
